/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.celularessuc.gco.ui;

import com.jjsoft.celularessuc.gco.mdl.DeudaCliente;
import com.jjsoft.celularessuc.gco.mdl.Mensualidad;
import com.jjsoft.celularessuc.gco.neg.DeudaClienteManager;
import com.jjsoft.celularessuc.gco.util.CNumeros;
import com.jjsoft.celularessuc.gco.util.DeudaClienteValidadorException;
import com.jjsoft.celularessuc.gco.util.MiModelo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;

/**
 *
 * @author javila
 */
public class VPlanificacionPagos extends javax.swing.JFrame {

    /**
     * Creates new form VPlanificacionPagos
     */
    List<Mensualidad> listaMensualidades;
    DeudaCliente deuda;
    DeudaClienteManager dcm = new DeudaClienteManager();

    public VPlanificacionPagos() {
        initComponents();
        Date d = new Date();
        if (d.getMonth() == 11) {
            d.setMonth(0);
            d.setYear(d.getYear() + 1);
        } else {
            d.setMonth(d.getMonth() + 1);
        }
        dtcPagoInicial.setDate(d);
    }

    public VPlanificacionPagos(DeudaCliente deuda) {
        initComponents();
        Date d = new Date();
        if (d.getMonth() == 11) {
            d.setMonth(0);
            d.setYear(d.getYear() + 1);
        } else {
            d.setMonth(d.getMonth() + 1);
        }
        dtcPagoInicial.setDate(d);
        txtCliente.setText(deuda.getCedulaCliente().getNombres() + " " + deuda.getCedulaCliente().getApellidos());
        txtCapital.setText(deuda.getMontoInicial().toString());
        txtCapital.setEditable(false);
        SpinnerModel modelo = new SpinnerNumberModel(0, 0, 1000, 0.1);
        txtInteres.setModel(modelo);
        this.deuda = deuda;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtCapital = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtInteres = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        txtMeses = new javax.swing.JSpinner();
        cmdCalcular = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgPagos = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        dtcPagoInicial = new com.toedter.calendar.JDateChooser();
        cmdCrearCredito = new javax.swing.JButton();
        cmdCancelar = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        txtCliente = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtCuota = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel6.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(0, 51, 255));
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("Planificación de Pago de Créditos");

        jLabel1.setText("Capital:");

        jLabel2.setText("Interes(Mensual): ");

        jLabel3.setText("N. Pagos(Meses):");

        cmdCalcular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/calculator.png"))); // NOI18N
        cmdCalcular.setText("Calcular");
        cmdCalcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCalcularActionPerformed(evt);
            }
        });

        dtgPagos.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        dtgPagos.setEnabled(false);
        jScrollPane1.setViewportView(dtgPagos);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 0, 0));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Detalle de Pagos");

        jLabel5.setText("Pago Inicial:");

        cmdCrearCredito.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/check.png"))); // NOI18N
        cmdCrearCredito.setText("Crear Crédito");
        cmdCrearCredito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCrearCreditoActionPerformed(evt);
            }
        });

        cmdCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdCancelar.setText("Cancelar");
        cmdCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCancelarActionPerformed(evt);
            }
        });

        jLabel7.setText("Cliente");

        txtCliente.setEditable(false);

        jLabel8.setText("Cuota Mensual:");

        txtCuota.setEditable(false);
        txtCuota.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtCuota.setForeground(new java.awt.Color(255, 0, 0));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(dtcPagoInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCliente))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtCapital, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtInteres, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtMeses, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cmdCalcular)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmdCrearCredito)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdCancelar))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCuota, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtCapital, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtInteres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(txtMeses, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdCalcular))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(dtcPagoInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel7)
                        .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtCuota, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdCrearCredito)
                    .addComponent(cmdCancelar))
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCalcularActionPerformed
        // TODO add your handling code here:
        double capital = Double.parseDouble(txtCapital.getText());
        double interes = Double.parseDouble(String.valueOf(txtInteres.getValue()));
        double meses = Double.parseDouble(String.valueOf(txtMeses.getValue()));
        double interesMensual = (interes) / 100;
        double cuota = (capital * interesMensual) / (1d - Math.pow((1d + interesMensual), (meses * -1)));
        //System.out.println(cuota);
        String[] identificiadores = {"Pago", "F. Pago", "S.Inicial", "Interes", "Capital", "Couta", "Saldo Final"};
        txtCuota.setText(CNumeros.Formato(cuota));
        listaMensualidades = new ArrayList<Mensualidad>();
        MiModelo modelo = new MiModelo();
        modelo.setColumnIdentifiers(identificiadores);
        double saldoActual;
        double interesActual;
        double capitalActual;
        double saldoFinal;
        saldoActual = capital;
        Date fecha = dtcPagoInicial.getDate();
        for (int i = 0; i < meses; i++) {
            String fechaDePago = fecha.toLocaleString().split(" ")[0];

            interesActual = saldoActual * interesMensual;
            capitalActual = cuota - interesActual;
            saldoFinal = saldoActual - capitalActual;

            String[] datos = {String.valueOf(i + 1), fechaDePago, CNumeros.Formato(saldoActual), CNumeros.Formato(interesActual), CNumeros.Formato(capitalActual), CNumeros.Formato(cuota), CNumeros.Formato(saldoFinal)};
            modelo.addRow(datos);

            Mensualidad mensualidad = new Mensualidad();
            mensualidad.setCapital(capitalActual);
            mensualidad.setCouta(cuota);
            mensualidad.setEstado(true);
            Date fechaActual = new Date();
            fechaActual.setMonth(fecha.getMonth());
            fechaActual.setYear(fecha.getYear());
            fechaActual.setDate(fecha.getDate());
            mensualidad.setFechaPago(fechaActual);
            mensualidad.setIdDeuda(deuda);
            mensualidad.setInteres(interesActual);
            mensualidad.setNumPago(i + 1);
            mensualidad.setPorcInteres(interesMensual);
            mensualidad.setSaldoFinal(saldoFinal);
            mensualidad.setSaldoInicial(saldoActual);

            saldoActual = saldoFinal;
            listaMensualidades.add(mensualidad);
            if (fecha.getMonth() == 11) {
                fecha.setMonth(0);
                fecha.setYear(fecha.getYear() + 1);
            } else {
                fecha.setMonth(fecha.getMonth() + 1);
            }

        }
        this.dtgPagos.setModel(modelo);
    }//GEN-LAST:event_cmdCalcularActionPerformed

    private void cmdCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_cmdCancelarActionPerformed

    private void cmdCrearCreditoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCrearCreditoActionPerformed
        if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro?", "Crear Crédito", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            try {
                dcm.guardarDeudaMensualidad(deuda, listaMensualidades);
                JOptionPane.showMessageDialog(rootPane, "Crédito creado correctamente", "Crear Crédito", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } catch (DeudaClienteValidadorException ex) {
                JOptionPane.showMessageDialog(rootPane, ex.getMessage().substring(ex.getMessage().toString().indexOf(":") + 1), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_cmdCrearCreditoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VPlanificacionPagos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VPlanificacionPagos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VPlanificacionPagos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VPlanificacionPagos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VPlanificacionPagos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdCalcular;
    private javax.swing.JButton cmdCancelar;
    private javax.swing.JButton cmdCrearCredito;
    private com.toedter.calendar.JDateChooser dtcPagoInicial;
    private javax.swing.JTable dtgPagos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtCapital;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtCuota;
    private javax.swing.JSpinner txtInteres;
    private javax.swing.JSpinner txtMeses;
    // End of variables declaration//GEN-END:variables
}
